<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户登录</title>
    <style>
        /* 保持原有样式不变 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: "微软雅黑", sans-serif;
        }

        body {
            background-color: #f5f5f5;
            padding: 50px 0;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .login-container {
            width: 400px;
            background-color: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        h1 {
            text-align: center;
            color: #333;
            margin-bottom: 25px;
            font-size: 24px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #666;
            font-size: 14px;
        }

        input {
            width: 100%;
            padding: 10px 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
            transition: border-color 0.3s;
        }

        input:focus {
            outline: none;
            border-color: #4a90e2;
            box-shadow: 0 0 0 2px rgba(74, 144, 226, 0.2);
        }

        .form-actions {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            font-size: 14px;
        }

        .form-actions label {
            display: inline-flex;
            align-items: center;
            margin-bottom: 0;
            cursor: pointer;
        }

        .form-actions input[type="checkbox"] {
            width: auto;
            margin-right: 5px;
        }

        .form-actions a {
            color: #4a90e2;
            text-decoration: none;
        }

        .form-actions a:hover {
            text-decoration: underline;
        }

        button {
            width: 100%;
            padding: 12px;
            background-color: #4a90e2;
            color: white;
            border: none;
            border-radius: 4px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        button:hover {
            background-color: #3a80d2;
        }

        .footer-text {
            text-align: center;
            margin-top: 20px;
            color: #999;
            font-size: 14px;
        }

        .footer-text a {
            color: #4a90e2;
            text-decoration: none;
        }

        .footer-text a:hover {
            text-decoration: underline;
        }

        /* 错误提示样式 */
        .error-message {
            color: #dc3545;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }
    </style>
</head>
<body>
<div class="login-container">
    <h1>用户登录</h1>
    <form id="loginForm">
        <div class="form-group">
            <label for="username">用户名</label>
            <input type="text" id="username" name="username" placeholder="请输入用户名" required>
            <div class="error-message" id="usernameError"></div>
        </div>
        <div class="form-group">
            <label for="password">密码</label>
            <input type="password" id="password" name="password" placeholder="请输入密码" required>
            <div class="error-message" id="passwordError"></div>
        </div>

        <div class="form-actions">
            <label>
                <input type="checkbox" id="rememberMe" name="rememberMe"> 记住我
            </label>
            <a href="/forgot-password.html">忘记密码？</a>
        </div>

        <button type="submit">登录</button>
        <p class="footer-text">还没有账号？<a href="/register.html">去注册</a></p>
    </form>
</div>

<script>
    const form = document.getElementById('loginForm');
    const usernameInput = document.getElementById('username');
    const passwordInput = document.getElementById('password');
    const usernameError = document.getElementById('usernameError');
    const passwordError = document.getElementById('passwordError');

    // 输入验证
    function validateInputs() {
        let isValid = true;

        if (!usernameInput.value.trim()) {
            usernameError.textContent = '请输入用户名';
            usernameError.style.display = 'block';
            isValid = false;
        } else {
            usernameError.style.display = 'none';
        }

        if (!passwordInput.value) {
            passwordError.textContent = '请输入密码';
            passwordError.style.display = 'block';
            isValid = false;
        } else {
            passwordError.style.display = 'none';
        }

        return isValid;
    }

    // 绑定验证事件
    usernameInput.addEventListener('blur', validateInputs);
    passwordInput.addEventListener('blur', validateInputs);

    form.addEventListener('submit', async (e) => {
        e.preventDefault();

        if (!validateInputs()) {
            return;
        }

        const formData = {
            username: usernameInput.value.trim(),
            password: passwordInput.value,
        };

        try {
            const response = await fetch('http://localhost:8080/auth/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            });

            if (response.ok) {
                const result = await response.json();
                // 保存token和过期时间
                const expiresAt = new Date().getTime() + 86400000; // 24小时，与后端配置一致
                localStorage.setItem('token', result.accessToken);
                localStorage.setItem('refreshToken', result.refreshToken); // 保存refreshToken
                localStorage.setItem('tokenExpiresAt', expiresAt);
                localStorage.setItem('userId', result.id);
                localStorage.setItem('username', formData.username);
                localStorage.setItem('isAdmin', result.admin);
                localStorage.setItem('loginTime', new Date().getTime().toString()); // 新增登录时间记录

                alert('登录成功！');
                window.location.href = '/index.html';
            } else {
                const error = await response.json().catch(() => ({}));
                // 明确提示令牌过期
                if (error.code === 'TOKEN_EXPIRED') {
                    alert('登录已过期，请重新登录');
                } else {
                    alert(`登录失败：${error.message || '用户名或密码错误'}`);
                }
            }
        } catch (error) {
            console.error('请求失败：', error);
            alert('网络错误，请稍后重试');
        }
    });
</script>
</body>
</html>